<template>
    <div class="chat-container">
        <div class="header">
            <el-button @click="router.back()">返回</el-button>
            <h1 class="title">DeepSeek</h1>
            <button class="settings-btn" @click="openSettings">⚙️</button>
        </div>
        <!-- 聊天窗口 -->
        <div class="chat-box" ref="chatBox">
            <div v-for="(message, index) in chatMessages" :key="index" :class="['message', message.role]">
                <img v-if="message.role === 'assistant'" :src="deepseekimg" class="chat-avatar" alt="AI 头像">
                <img v-else :src="`${config.downloadUrl}?name=${avatar}`" class="chat-avatar" alt="用户头像">
                <div class="bubble-container">
                    <v-md-preview v-if="message.role === 'assistant'" :text="message.content" />
                    <p v-else>{{ message.content }}</p>
                </div>
            </div>
            <div v-if="streamingMessage" class="message assistant">
                <img :src="deepseekimg" class="chat-avatar" alt="AI 头像">
                <div class="bubble-container">
                    <v-md-preview :text="streamingMessage" />
                </div>
            </div>
        </div>

        <div v-if="loading" class="loading">AI 正在思考中...</div>
        <div v-if="error" class="error">请求失败或者您还没有设置您的apikey，请重试。</div>

        <!-- 输入框 -->
        <div class="input-box">
            <input v-model="userMessage" placeholder="来通过DeepSeek获取一些灵感吧" @keyup.enter="sendMessage" />
            <button @click="sendMessage" :disabled="loading">发送</button>
        </div>
    </div>

    <el-dialog v-model="settingsOpen" title="API 设置">
        <el-input v-model="apiKey" placeholder="请输入您的 DeepSeek API Key" />
        <template #footer>
            <el-button @click="saveApiKey">保存</el-button>
            <el-button type="danger" @click="confirmClearHistory">清空记录</el-button>
        </template>
    </el-dialog>
</template>

<script setup>
import { ref, nextTick, onMounted, watch } from 'vue'
import { getChatStream } from '@/api/deepseekApi'
import config from '../../../../public/config'
import { getuserMessage } from '../../../api/user'
import deepseekimg from '../../../../public/deepseek.png'
import { ElMessageBox, ElMessage } from 'element-plus'
import router from '../../../router'


const chatMessages = ref(JSON.parse(localStorage.getItem('deepseekChatHistory') || '[]'))
const userMessage = ref('')
const streamingMessage = ref('')
const loading = ref(false)
const error = ref(null)
const chatBox = ref(null)
const avatar = ref('')

const settingsOpen = ref(false)
const apiKey = ref(localStorage.getItem('deepseekApiKey') || '')

onMounted(() => {
    getUser()
})

function openSettings() {
    settingsOpen.value = true;
}
function confirmClearHistory() {
    ElMessageBox.confirm('确定要删除所有聊天记录吗？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        chatMessages.value = []
        ElMessage.success('聊天记录已清空')
    }).catch(() => { })
}

function saveApiKey() {
    localStorage.setItem('deepseekApiKey', apiKey.value)
    settingsOpen.value = false;
}

// 新增保存聊天记录的方法
function saveChatHistory() {
    localStorage.setItem(
        'deepseekChatHistory',
        JSON.stringify(chatMessages.value)
    )
}

// 在消息数组变化时自动保存
watch(chatMessages, saveChatHistory, { deep: true })

async function sendMessage() {
    if (!userMessage.value.trim()) return;

    chatMessages.value.push({ role: 'user', content: userMessage.value });
    streamingMessage.value = '';
    loading.value = true;
    error.value = null;

    try {
        const messages = [
            { role: 'system', content: 'You are a helpful assistant.' },
            ...chatMessages.value,
            { role: 'user', content: userMessage.value },
        ];

        userMessage.value = '';

        const key = localStorage.getItem('deepseekApiKey')
        if (!key) {
            error.value = '请先设置 API Key';
            return;
        }

        const stream = await getChatStream(messages, key);

        for await (const chunk of stream) {
            streamingMessage.value += chunk;
            scrollToBottom();
        }

        // 流式响应完成后
        chatMessages.value.push({
            role: 'assistant',
            content: streamingMessage.value
        });
        streamingMessage.value = '';
    } catch (err) {
        error.value = '请先输入ApiKey或请求失败请重试。';
        console.error(err);
    } finally {
        loading.value = false;
    }
}

async function scrollToBottom() {
    await nextTick()
    if (chatBox.value) {
        chatBox.value.scrollTop = chatBox.value.scrollHeight
    }
}

async function getUser() {
    const params = new URLSearchParams()
    params.append('id', localStorage.getItem('userId'))
    const res = await getuserMessage(params)
    avatar.value = res.data.avatar
}
</script>

<style scoped>
/* 整体容器样式 */
.chat-container {
    width: 70%;
    margin: 0 auto;
    padding: 20px;
    font-family: "Poppins", Arial, sans-serif;
    background: #fff;
    border-radius: 10px;
    box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.1);
    transition: width 0.3s ease;
    margin-top: 40px;
}

/* 头部样式 */
.header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px;
    border-bottom: 2px solid #e5e5e5;
}

.title {
    flex-grow: 1;
    text-align: center;
    font-size: 26px;
    font-weight: bold;
    color: #333;
}

.settings-btn {
    background: none;
    border: none;
    font-size: 24px;
    cursor: pointer;
    color: #666;
    transition: color 0.3s;
}

.settings-btn:hover {
    color: #000;
}

.el-button {
    margin-left: 10px;
}

/* 聊天窗口样式 */
.chat-box {
    width: 98%;
    height: 600px;
    max-height: 80vh;
    overflow-y: auto;
    padding: 15px;
    border-radius: 15px;
    /* 增加圆角 */
    background: #fafafa;
    display: flex;
    flex-direction: column;
    gap: 15px;
    /* 增加消息之间的间距 */
    scrollbar-width: thin;
    scrollbar-color: #ccc transparent;
    transition: width 0.3s ease;
    box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.1);
    /* 增加内阴影 */
}

/* Webkit（Chrome, Edge, Safari）自定义滚动条 */
.chat-box::-webkit-scrollbar {
    width: 10px;
    /* 增加滚动条宽度 */
}

.chat-box::-webkit-scrollbar-thumb {
    background: #888;
    /* 改变滚动条颜色 */
    border-radius: 5px;
    /* 增加滚动条圆角 */
    transition: background 0.3s;
}

.chat-box::-webkit-scrollbar-thumb:hover {
    background: #666;
}

.chat-box::-webkit-scrollbar-track {
    background: transparent;
}

/* 消息样式 */
.message {
    display: flex;
    align-items: flex-start;
    max-width: 85%;
    gap: 12px;
    position: relative;
    /* 移除背景色和padding */
    background: none !important;
    padding: 0 !important;
    margin: 8px 0;
}

/* 用户消息调整 */
.message.user {
    flex-direction: row-reverse;
    align-self: flex-end;
    margin-left: auto;
}

.bubble-container {
    max-width: calc(100% - 60px);
    /* 将气泡样式移到容器 */
    background: linear-gradient(135deg, #007bff, #0056b3);
    color: white;
    padding: 12px 20px;
    border-radius: 20px;
}

.message.assistant .bubble-container {
    background: #e9f5ff;
    color: #333;
}

.message.user .bubble-container {
    text-align: right;
}

/* 调整原有消息样式 */
.message.user {
    background: linear-gradient(135deg, #007bff, #0056b3);
    color: white;
    padding: 12px 20px;
    border-radius: 20px;
    margin: 8px 0;
}

.message.assistant {
    background: #e9f5ff;
    color: #333;
    padding: 12px 20px;
    border-radius: 20px;
    margin: 8px 0;
}

/* 加载提示样式 */
.loading {
    text-align: center;
    font-size: 14px;
    color: #666;
    margin-top: 10px;
}

/* 输入框样式 */
.input-box {
    display: flex;
    gap: 10px;
    margin-top: 15px;
    padding: 10px;
    background: #fff;
    border-top: 2px solid #e5e5e5;
    border-radius: 0 0 10px 10px;
}

input {
    flex: 1;
    padding: 12px;
    border: 2px solid #ddd;
    border-radius: 25px;
    font-size: 16px;
    outline: none;
    transition: border-color 0.3s, box-shadow 0.3s;
}

input:focus {
    border-color: #007bff;
    box-shadow: 0px 0px 5px rgba(0, 123, 255, 0.5);
}

button {
    padding: 12px 20px;
    background: linear-gradient(135deg, #007bff, #0056b3);
    color: white;
    border: none;
    border-radius: 25px;
    cursor: pointer;
    font-size: 16px;
    font-weight: bold;
    transition: background 0.3s, transform 0.2s;
}

button:hover {
    background: linear-gradient(135deg, #0056b3, #003f7f);
    transform: scale(1.05);
}

button:disabled {
    background: #ccc;
    cursor: not-allowed;
}

/* 对话框样式 */
.el-dialog {
    transition: all 0.3s ease;
}

.el-dialog__header {
    background: #f8f8f8;
    border-bottom: 1px solid #e5e5e5;
}

.el-dialog__title {
    font-size: 18px;
    font-weight: bold;
    color: #333;
}

.el-dialog__body {
    padding: 20px;
}

.el-dialog__footer {
    border-top: 1px solid #e5e5e5;
    padding: 15px 20px;
    text-align: right;
}

.el-input {
    width: 100%;
}

.el-button {
    padding: 10px 20px;
    border-radius: 5px;
    font-size: 14px;
    font-weight: bold;
    transition: background 0.3s, transform 0.2s;
}

.el-button--primary {
    background: linear-gradient(135deg, #007bff, #0056b3);
    color: white;
    border: none;
}

.el-button--primary:hover {
    background: linear-gradient(135deg, #0056b3, #003f7f);
    transform: scale(1.05);
}

.chat-avatar {
    width: 50px;
    height: 50px;
    border-radius: 50%;
    margin-right: 10px;
}
</style>
